package com.swpu.service_sleep.controller;


import com.swpu.commonutils.JwtUtils;
import com.swpu.commonutils.R;
import com.swpu.commonutils.ResultEncryption;
import com.swpu.service_sleep.entity.SleepRecord;
import com.swpu.service_sleep.entity.SleepRecordVo;
import com.swpu.service_sleep.entity.SleepVo;
import com.swpu.service_sleep.service.SleepRecordService;
import com.swpu.service_user.aop.Decrypt;
import com.swpu.service_user.aop.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chaichai
 * @since 2024-02-18
 */
@RestController
@RequestMapping("/service_sleep/sleep-record")
public class SleepRecordController {
    @Autowired
    private SleepRecordService sleepRecordService;
    @PostMapping("/saveUserSleepData")
    @Decrypt
    @Encrypt
    public R saveUserSleepData(@RequestBody ResultEncryption resultEncryption,  SleepRecord sleepRecord, HttpServletRequest request){
        String openid = JwtUtils.getOpenidByJwtToken(request);
        if (openid.isEmpty()){
            return R.error().message("当前用户无访问权限");
        }
        this.sleepRecordService.saveUserSleepData(sleepRecord,openid);
        return R.ok();
    }
    @GetMapping("/getUserMonthData")
    public R getUserMonthData(HttpServletRequest request,String dayStr){
        String openid = JwtUtils.getOpenidByJwtToken(request);
        if (openid.isEmpty()){
            return R.error().message("当前用户无访问权限");
        }
        List<SleepVo> SleepVos = this.sleepRecordService.getUserMonthData(openid, dayStr);
        return R.ok().data("monthSleepData",SleepVos);
    }
    @GetMapping("/getUserSleepChartData")
    public R getUserSleepChartData(HttpServletRequest request, @RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "7") Integer pageSize){
        String openid = JwtUtils.getOpenidByJwtToken(request);
        if (openid.isEmpty()){
            return R.error().message("当前用户无访问权限");
        }
        SleepRecordVo userSleepChartDataVo = this.sleepRecordService.getUserSleepChartData(openid, page, pageSize);
        return R.ok().data("sleepChartData",userSleepChartDataVo);
    }
    @GetMapping("/getAugSleepHour")
    public R getAvgSleepHour(HttpServletRequest request,@RequestParam(defaultValue = "7") Integer days){
        String openid = JwtUtils.getOpenidByJwtToken(request);
        if (openid.isEmpty()){
            return R.error().message("当前用户未登录");
        }
        Double avgSleepHour = sleepRecordService.getAvgSleepHour(openid, days);
        return R.ok().data("avgSleepHour",avgSleepHour);
    }

}

